package com.authine.cloudpivot.web.api.secondopen.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.authine.cloudpivot.web.api.config.HxConfig;
import com.authine.cloudpivot.web.api.secondopen.modules.DysqParamVO;
import com.authine.cloudpivot.web.api.secondopen.modules.PartInfoVO;
import com.authine.cloudpivot.web.api.secondopen.modules.QadResultVO;
import com.authine.cloudpivot.web.api.secondopen.service.ProductionManagementService;
import com.authine.cloudpivot.web.api.secondopen.utils.HttpRestUtil;
import com.authine.cloudpivot.web.api.utils.StringUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.http.HttpEntity;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ProductionManagementServiceImpl  implements ProductionManagementService {

    private static final Logger log = LoggerFactory.getLogger(ProductionManagementServiceImpl.class);


    @Autowired
    private HxConfig hxConfig;


    @Override
    public List<PartInfoVO> getPartInfo(String parts) {
        //String url = hxConfig.getQadurl();
        String xdomain =hxConfig.getXdomain();
        String url="http://192.9.200.79:9092/api/CommonMaster/Get";
        String xtoken="8c2e513b-3517-978f-96db-86edea680f98";
        String xcode="qad_pt_mstr";
        //String xtoken = hxConfig.getToken();
        //拼接请求url
        url=url+"?qad_pt_part="+parts;
        String result = HttpRestUtil.httpGetUrlWithoutEncrypt(url,"", xdomain, xcode, xtoken);
        log.info("------------------------"+ JSON.toJSONString(result));
        JSONObject jsonObject = JSONObject.parseObject(result);
        List<PartInfoVO> partInfoVOS=new ArrayList<>();
        if (!org.apache.commons.lang.StringUtils.isEmpty(result)){
            JSONArray data = jsonObject.getJSONArray("data");
            log.info("--------列表接口返回：",data);
            if (!CollectionUtils.isEmpty(data)) {
                for (int i = 0; i < data.size(); i++) {
                    JSONObject object = (JSONObject) data.get(i);
                    PartInfoVO partInfoVO = new PartInfoVO();
                    //id
                    partInfoVO.setId(object.getString("qad_pt_part"));
                    //零件号
                    partInfoVO.setPart( object.getString("qad_pt_part") );
                    //零件名
                    partInfoVO.setName(object.getString("qad_pt_desc1"));
                    //规格
                    partInfoVO.setSpecs(object.getString("qad_pt_desc2"));
                    //环径
                    partInfoVO.setLd(object.getString("qad_pt_ld"));
                    //环别
                    partInfoVO.setLc(object.getString("qad_pt_lc"));
                    //表面处理
                    partInfoVO.setSt(object.getString("qad_pt_st"));
                    //材质
                    partInfoVO.setMq(object.getString("qad_pt_mq"));
                    //市场
                    partInfoVO.setMarket(object.getString("qad_pt_market"));
                    partInfoVOS.add(partInfoVO);
                }
            }
        }
        return partInfoVOS;
    }

    @Override
    public QadResultVO sendDysqToMes(DysqParamVO dysqParamVO,String czfs) {
        //生产环境
//        String url = "http://192.9.200.79:9093/api/";
//        String xtoken = "8c2e513b-3517-978f-96db-86edea680f98";
        String url = hxConfig.getQadurlheader();
        String xtoken =hxConfig.getToken();
        String xdomain =hxConfig.getXdomain();
        String xcode=null;

        String result=null;
        //操作方式为新增
        if(czfs.equals("新增")){
             xcode="MdmYpslMstrPost";
             url=url+"MdmYpslMstr/Post";
             result =HttpRestUtil.httpPostUrlWithoutEncryptInLogin(url,"",xdomain,xcode,xtoken,JSON.toJSONString(dysqParamVO));
        }
        if (czfs.equals("修改")){
            xcode="MdmYpslMstrPut";
            url=url+"MdmYpslMstr/Put";
            Map<String,String> map=new HashMap<>();
            map.put("x-corp","");
            map.put("x-domain",xdomain);
            map.put("x-code",xcode);
            map.put("x-token",xtoken);
            String s=JSON.toJSONString(dysqParamVO);
            result = doPutHttpRequest(url, map, s);
        }
        log.info("------------------------"+JSON.toJSONString(result));
        JSONObject jsonObject = JSONObject.parseObject(result);
        QadResultVO qadResultVO=new QadResultVO();
        if (StringUtils.isNotBlank(result)) {
            String code=jsonObject.getString("code");
            String msg=jsonObject.getString("msg");
            JSONArray data = jsonObject.getJSONArray("data");
            qadResultVO.setCode(code);
            qadResultVO.setMsg(msg);
            qadResultVO.setData(data);
            log.info("**列表接口返回:{}", JSON.toJSONString(qadResultVO));
        }
        return qadResultVO;
    }

    //httpput请求方法
    public String doPutHttpRequest(String url, Map<String, String> headerMap,String requestBody) {
                 CloseableHttpClient httpClient = HttpClients.createDefault();
                   String entityStr = null;
                   CloseableHttpResponse response = null;
                     try {
                             HttpPut post = new HttpPut(url);
                          //添加头部信息
                           for (Map.Entry<String, String> header : headerMap.entrySet()) {
                                   post.addHeader(header.getKey(), header.getValue());
                                 }
                             HttpEntity entity = new StringEntity(requestBody, ContentType.APPLICATION_JSON);
                            System.out.println("请求体是："+requestBody);
                            post.setEntity(entity);
                             response = httpClient.execute(post);
                             // 获得响应的实体对象
                             HttpEntity httpEntity = response.getEntity();
                             // 使用Apache提供的工具类进行转换成字符串
                             entityStr = EntityUtils.toString(httpEntity, "UTF-8");
                             System.out.println("PUT请求路径："+post);
                             System.out.println("PUT请求结果："+entityStr);
                         } catch (ClientProtocolException e) {
                             System.err.println("Http协议出现问题");
                             e.printStackTrace();
                         } catch (ParseException e) {
                             System.err.println("解析错误");
                             e.printStackTrace();
                         } catch (IOException e) {
                             System.err.println("IO异常");
                             e.printStackTrace();
                         }
                     return entityStr;
                 }

    @Override
    public List<PartInfoVO> getSAByCA(String domain, String compfr, String compto) {
        String url = hxConfig.getQadurl();
        String xdomain =hxConfig.getXdomain();
        String xcode="qad_zps_mstr";
        String xtoken = hxConfig.getToken();
        url=url+"?qad_zps_domain="+domain+"&"+"qad_zps_compFr="+compfr+"&"+"qad_zps_compTo="+compto;
        String result = HttpRestUtil.httpGetUrlWithoutEncrypt(url,"", xdomain, xcode, xtoken);
        log.info("------------------------"+ JSON.toJSONString(result));
        JSONObject jsonObject = JSONObject.parseObject(result);
        List<PartInfoVO> partInfoVOS=new ArrayList<>();
        if (!StringUtils.isEmpty(result)){
            JSONArray data = jsonObject.getJSONArray("data");
            log.info("--------列表接口返回：",data);
            if (!CollectionUtils.isEmpty(data)) {
                for (int i = 0; i < data.size(); i++) {
                    JSONObject object = (JSONObject) data.get(i);
                    PartInfoVO partInfoVO = new PartInfoVO();
                    //id
                    partInfoVO.setId(object.getString("qad_zps_par"));
                    //sa码
                    partInfoVO.setPart(object.getString("qad_zps_par"));
                    //描述
                    partInfoVO.setName(object.getString("qad_zps_par_desc1"));
                    partInfoVOS.add(partInfoVO);
                }
            }
        }
        return partInfoVOS;
    }
}
